import { AdminLayout } from '@/components/Layout';
import Head from 'next/head';
import { useState, useRef } from 'react';
import type { Category } from '@prisma/client';
import { requestMsg } from '@/components/server/utils/request';
import type { Data } from '@/pages/api/post/categories/list';
import type { Data as EditData } from '@/pages/api/post/categories/edit';
import { Button, Form, Tag, Popconfirm } from 'antd';
import { getLangByIntl } from '@/components/utils/locale';
import { useIntl, FormattedMessage } from 'react-intl';
import {
  ProList,
  ModalForm,
  ProFormText,
  ProFormSwitch,
  ProFormDateTimePicker,
  ActionType,
} from '@ant-design/pro-components';

export default function Index() {
  const [form] = Form.useForm();
  const intl = useIntl();
  const lang = getLangByIntl(intl);
  const editForm = (item: Category) => {
    form.setFieldsValue(item);
    setModalVisible(true);
    ref.current?.reload();
  };
  const handleDelete = (id: number) => {
    requestMsg<EditData>('/api/post/categories/delete', {
      method: 'post',
      data: { id },
    })
      .then((data) => {
        console.log(data);
        setModalVisible(false);
        ref.current?.reload();
      })
      .catch((err) => {
        console.error(err);
      });
  };
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const ref = useRef<ActionType>();
  return (
    <>
      <Head>
        <link
          rel="shortcut icon"
          type="image/x-icon"
          href="https://unpkg.byted-static.com/latest/byted/arco-config/assets/favicon.ico"
        />
        <title>{intl.formatMessage({ id: 'post.category.title' })}</title>
      </Head>
      <ProList<Category>
        headerTitle={intl.formatMessage({ id: 'post.category.title' })}
        search={{}}
        itemLayout="vertical"
        grid={{ gutter: 16, column: 2 }}
        actionRef={ref}
        metas={{
          title: {
            dataIndex: 'cat',
            title: <FormattedMessage id="post.category.field.name" />,
          },
          content: {
            render: (_, index) => (
              <>{index.reqLogin == true ? <Tag>私有</Tag> : '-'}</>
            ),
            search: false,
          },
          description: {
            dataIndex: 'createAt',
            valueType: 'dateTime',
            search: false,
          },
          actions: {
            cardActionProps: 'extra',
            render: (_, r) => [
              <Button
                key="run"
                type="link"
                onClick={() => {
                  editForm(r);
                }}
              >
                <FormattedMessage id="form.edit" />
              </Button>,

              <Popconfirm
                key="form.delete"
                title={intl.formatMessage({ id: 'form.delete' })}
                description={intl.formatMessage({ id: 'delete.confirm' })}
                onConfirm={() => {
                  handleDelete(r.id);
                }}
                okText={intl.formatMessage({ id: 'form.ok' })}
                cancelText={intl.formatMessage({ id: 'form.close' })}
              >
                <Button danger type="link">
                  <FormattedMessage id="form.delete" />
                </Button>
              </Popconfirm>,
            ],
          },
        }}
        toolBarRender={() => {
          return [
            <Button
              key="3"
              type="primary"
              onClick={() => {
                editForm({
                  reqLogin: false,
                  cat: '',
                  id: 0,
                  createAt: new Date(),
                  updatedAt: new Date(),
                });
              }}
            >
              <FormattedMessage id="form.new"></FormattedMessage>
            </Button>,
          ];
        }}
        request={async (params = {} as Record<string, string>) => {
          return requestMsg<Data>('/api/post/categories/list', {
            method: 'post',
            data: { page: params.current, size: params.pageSize },
            lang,
          }).then((ret) => {
            return Promise.resolve({
              ...ret,
              data: ret.categories,
            });
          });
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: false,
        }}
      ></ProList>
      <ModalForm<Category>
        title={intl.formatMessage({ id: 'post.edit.Title' })}
        open={modalVisible}
        onOpenChange={setModalVisible}
        submitter={{
          searchConfig: {
            resetText: intl.formatMessage({ id: 'form.close' }),
          },
        }}
        onFinish={async (values) => {
          requestMsg<EditData>('/api/post/categories/edit', {
            method: 'post',
            data: values,
          }).then(() => {
            setModalVisible(false);
            ref.current?.reload();
          });
        }}
        form={form}
      >
        <ProFormText name="id" hidden />
        <ProFormText
          name="cat"
          label={intl.formatMessage({ id: 'post.category.field.name' })}
          tooltip="最长为 24 位"
          placeholder={intl.formatMessage({ id: 'post.category.field.name' })}
        />
        <ProFormSwitch
          name="reqLogin"
          label={intl.formatMessage({ id: 'post.category.reqLogin' })}
          placeholder="请输入名称"
        />
        <ProFormDateTimePicker
          name="createAt"
          label={intl.formatMessage({ id: 'form.createTime' })}
          placeholder={intl.formatMessage({ id: 'form.createTime' })}
        />
        <ProFormDateTimePicker
          name="updatedAt"
          label={intl.formatMessage({ id: 'form.updateTime' })}
          placeholder={intl.formatMessage({ id: 'form.updateTime' })}
        />
      </ModalForm>
    </>
  );
}
Index.Layout = AdminLayout;
